﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Transactions;
using FriendsNearby.Services.Entities;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace FriendsNearby.Services.Tests
{
    [TestFixture]
    public class DataAccessFixture
    {
        TransactionScope testContextTransaction;
        DataAccess dataAccess;

        [SetUp]
        public void SetUp()
        {
            testContextTransaction = testContextTransaction = Protocols.TemporalyClearDatabase();
            dataAccess = new DataAccess();
        }

        [TearDown]
        public void TearDown()
        {
            testContextTransaction.Dispose();
        }

        [Test]
        public void ShouldReadStoredUserPreferences()
        {
            Guid userID = Guid.NewGuid();

			dataAccess.SetUserPreferences(userID, null, 50, VisibilityLevel.OnlyFriends);

			var stored = dataAccess.ReadUserPreferences(userID);
			Assert.AreEqual(userID, stored.UserID);
            Assert.AreEqual(50, stored.NearbyRadiusKM);
        }


        [Test]
        public void ShouldBeAbleToUpdateExistingUserPreferences()
        {
			Guid userID = Guid.NewGuid();
			
			dataAccess.SetUserPreferences(userID, null, 50, VisibilityLevel.OnlyFriends);

			dataAccess.SetUserPreferences(userID, null, 100, VisibilityLevel.OnlyFriends);

			var stored = dataAccess.ReadUserPreferences(userID);
			Assert.AreEqual(userID, stored.UserID);
            Assert.AreEqual(100, stored.NearbyRadiusKM);
        }

        [Test]
        public void ShouldCreateANonExistingUser()
        {
            var r = dataAccess.EnsureUserExists("TestUser1", "123456","a");
            Assert.IsTrue(r);
            Assert.AreEqual(dataAccess.GetUserSessionKey("TestUser1"), "123456");
        }

        [Test]
        public void ShouldChangeTheSessionKeyOfAnExistingUser()
        {
            var r1 = dataAccess.EnsureUserExists("TestUser1", "123456", "a");
            Assert.IsTrue(r1);
            var r2 = dataAccess.EnsureUserExists("TestUser1", "123", "a");
            Assert.IsFalse(r2);
            Assert.AreEqual(dataAccess.GetUserSessionKey("TestUser1"), "123");
        }

        [Test]
        public void ShouldChangeTheSessionKeyOfAnExistingUserWithDifferentDataAccess()
        {
            DataAccess otherDataAccess = new DataAccess();
            dataAccess.EnsureUserExists("TestUser1", "123456", "a");
            otherDataAccess.EnsureUserExists("TestUser1", "123", "a");
            Assert.AreEqual(dataAccess.GetUserSessionKey("TestUser1"), "123");
        }
    }
}
